
package com.ls.es;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("es/")
public class EsController {

	@Autowired
	private TransportClient client;

	@GetMapping("get/{id}")
	public ResponseEntity<Map> get(@PathVariable(name = "id") String id) {
		GetResponse getResponse = client.prepareGet("people2", "man", id).get();
		return new ResponseEntity<Map>(getResponse.getSource(), HttpStatus.OK);
	}

	@PostMapping("add")
	public ResponseEntity add(@RequestParam(name = "name") String name, @RequestParam(name = "age") String age,
			@RequestParam(name = "country") String country, @RequestParam(name = "date") String date)
			throws IOException {
		XContentBuilder content = XContentFactory.jsonBuilder().startObject().field("name", name).field("age", age)
				.field("country", country).field("date", date).endObject();

		IndexResponse indexResponse = client.prepareIndex("people2", "man").setSource(content).get();
		return new ResponseEntity(indexResponse.getId(), HttpStatus.OK);
	}

	@DeleteMapping("del/{id}")
	public ResponseEntity del(@PathVariable(name = "id") String id) {
		DeleteResponse delResponse = client.prepareDelete("people2", "man", id).get();
		return new ResponseEntity(delResponse.getResult(), HttpStatus.OK);
	}

	@PutMapping("update")
	public ResponseEntity update(@RequestParam(name = "id") String id,
			@RequestParam(name = "name", required = false) String name,
			@RequestParam(name = "country", required = false) String country,
			@RequestParam(name = "age", required = false) Integer age,
			@RequestParam(name = "date", required = false) String date)
			throws IOException, InterruptedException, ExecutionException {
		UpdateRequest request = new UpdateRequest("people2", "man", id);
		XContentBuilder content = XContentFactory.jsonBuilder().startObject();
		if (StringUtils.isNotBlank(name))
			content.field("name", name);
		if (StringUtils.isNotBlank(country))
			content.field("country", country);
		if (StringUtils.isNotBlank(date))
			content.field("date", date);
		if (age!=null)
			content.field("age", age);
		content.endObject();
		request.doc(content);
		UpdateResponse delResponse = client.update(request).get();
		return new ResponseEntity(delResponse.getResult(), HttpStatus.OK);
	}
	
	@PostMapping("query")
	public ResponseEntity query(
			@RequestParam(name = "name", required = false) String name,
			@RequestParam(name = "country", required = false) String country,
			@RequestParam(name = "max", required = true) int max ,
	@RequestParam(name = "min", required = false) Integer min)
			throws IOException, InterruptedException, ExecutionException {
		BoolQueryBuilder builder = QueryBuilders.boolQuery();
		if(StringUtils.isNotBlank(name))
		builder.must(QueryBuilders.matchQuery("name", name));
		if(StringUtils.isNotBlank(country))
		builder.must(QueryBuilders.matchQuery("country", country));
		
		RangeQueryBuilder rqb = QueryBuilders.rangeQuery("age"); //范围查询
		rqb.from(0);
		rqb.to(max);
		if(min!=null&&min>0){
			rqb.from(min);
		}
		builder.filter(rqb); //添加过滤条件，这里等级同must
		
		SearchRequestBuilder  sbuilder = client.prepareSearch("people2").setTypes("man").
		setQuery(builder).
		setSearchType(SearchType.DFS_QUERY_THEN_FETCH).
		setFrom(0).setSize(10);
		
		System.out.println(sbuilder);;
		
		SearchResponse  sr = sbuilder.get();
		SearchHit[] hs = sr.getHits().getHits();
		List<Map<String,Object>> maps = new LinkedList<Map<String,Object>>();
		for(SearchHit h:hs){
			maps.add(h.getSource());
		}
		return new ResponseEntity(maps, HttpStatus.OK);
	}
	
}
